package org.rrs.duker.api;

import android.text.LoginFilter;
import android.util.Log;

import com.android.volley.Response;
import com.android.volley.VolleyError;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.rrs.duker.net.NetCallBack;
import org.rrs.duker.net.NetManager;
import org.rrs.duker.pojo.Category;
import org.rrs.duker.pojo.Subscribe;
import org.rrs.duker.pojo.SummaryInfo;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by meiming on 16-7-2.
 */
public class FeedlyApiHelper extends AbsApiHelper {
    private static final String TAG = "FeedlyApiHelper";

    private static final String API_TOKEN_TEST = "A02zIqzHCWZYnv7COHVU_35gtKVDWj12SWvzyaxIRRItoVy2OpnRvx4TgSuzTRV3_8hCgJ64mHxtuFrpMyqeD_1coSjrgMhs_mLLOdG67tba0OXoNyK6POI-C2wm80iB0bwAaFLqU8ZKsYV_PZdgxCkc2EuXGcG9RO_XMSK7-8pAam8U8coWn_6yKjyVf_u1erpAlwyqqAvpa85QjRunhBmL1v8PEQ:feedlydev";
    private static final String API_HOST_URL = "https://cloud.feedly.com";
    private static final String API_PROFILE_URL = "/v3/profile";
    private static final String API_SUBSCRIPTIONS_URL = "/v3/subscriptions";
    private static final String API_CATEGORIES_URL = "/v3/categories";
    private static final String API_ENTRIES_URL = "/v3/entries/:entryId";
    private static final String API_STREAMS_IDS_URL = "/v3/streams/ids?streamId=:streamId";
    private static final String API_STREAMS_CONTENTS_URL = "/v3/streams/contents?streamId=:streamId";

    @Override
    public void getCategoryList(String token, final NetCallBack<Category> netCallBack) {
        token = API_TOKEN_TEST;
        String requestUrl = API_HOST_URL + API_CATEGORIES_URL;

        Map<String, String> header = new HashMap<>();
        header.put("Authorization","OAuth " + token);

        NetManager.newInstance().requestString(requestUrl, header, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                List<Category> categoryList = parserCategoryList(response);
                Log.i(TAG, "onResponse: " + categoryList.toString());
                if(netCallBack != null){
                    netCallBack.onSuccess(categoryList);
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.i(TAG, "onErrorResponse: " + error.getMessage());
                if (netCallBack != null) {
                    netCallBack.onError(error.getMessage());
                }
            }
        });
    }

    @Override
    public void getSubscribeList(String token, final NetCallBack<Subscribe> netCallBack) {
        token = API_TOKEN_TEST;
        String requestUrl = API_HOST_URL + API_SUBSCRIPTIONS_URL;

        Map<String, String> header = new HashMap<>();
        header.put("Authorization","OAuth " + token);

        NetManager.newInstance().requestString(requestUrl, header, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                List<Subscribe> subscribeList = parserSubscribeList(response);
                Log.i(TAG, "onResponse: " + subscribeList.toString());
                if(netCallBack != null){
                    netCallBack.onSuccess(subscribeList);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.i(TAG, "onErrorResponse: " + error.getMessage());
                if (netCallBack != null) {
                    netCallBack.onError(error.getMessage());
                }
            }
        });
    }

    @Override
    public void getSummaryInfoList(String token, String feedId, final NetCallBack<SummaryInfo> netCallBack) {
        token = API_TOKEN_TEST;
        String requestUrl = API_HOST_URL + API_STREAMS_CONTENTS_URL.replace(":streamId", feedId);

        Map<String, String> header = new HashMap<>();
        header.put("Authorization","OAuth " + token);

        NetManager.newInstance().requestString(requestUrl, header, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                List<SummaryInfo> summaryInfoList = parserSummaryInfoList(response);
                Log.i(TAG, "onResponse: " + summaryInfoList.toString());
                if(netCallBack != null){
                    netCallBack.onSuccess(summaryInfoList);
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.i(TAG, "onErrorResponse: " + error.getMessage());
                if (netCallBack != null) {
                    netCallBack.onError(error.getMessage());
                }
            }
        });
    }

    private List<Category> parserCategoryList(String data){
        Log.i(TAG, "parserCategoryList: "+data);
        List<Category> categoryList = new ArrayList<>();
        try{
            JSONArray jsonData = new JSONArray(data);
            for (int i = 0; i < jsonData.length(); ++i){
                JSONObject obj = jsonData.getJSONObject(i);
                Category category = new Category();
                category.setId(obj.getString("id"));
                category.setLabel(obj.getString("label"));
                //category.setDescription(obj.getString("description"));
                categoryList.add(category);
            }
        } catch (JSONException e){
            e.printStackTrace();
        }

        return categoryList;
    }

    private List<Subscribe> parserSubscribeList(String data){
        Log.i(TAG, "parserSubscribeList: "+data);
        List<Subscribe> subscribeList = new ArrayList<>();
        try{
            JSONArray jsonData = new JSONArray(data);
            for (int i = 0; i < jsonData.length(); ++i){
                JSONObject obj = jsonData.getJSONObject(i);
                Subscribe subscribe = new Subscribe();
                subscribe.setFeedId(obj.getString("id"));
                subscribe.setName(obj.getString("title"));
                subscribe.setUrl(obj.getString("website"));
                List<String> categoryIdList = new ArrayList<>();
                JSONArray categories = obj.getJSONArray("categories");
                for (int j = 0; j < categories.length(); ++j){
                    categoryIdList.add(categories.getJSONObject(j).getString("id"));
                }
                subscribe.setCategoryIds(categoryIdList);
                subscribeList.add(subscribe);
            }
        } catch (JSONException e){
            e.printStackTrace();
        }
        return subscribeList;
    }


    private List<SummaryInfo> parserSummaryInfoList(String data){
        Log.i(TAG, "parserSubscribeList: "+data);
        List<SummaryInfo> summaryInfoList = new ArrayList<>();
        try{
            JSONObject obj = new JSONObject(data);
            JSONArray jsonData = obj.getJSONArray("items");
            for (int i = 0; i < jsonData.length(); ++i){
                JSONObject jsonObj = jsonData.getJSONObject(i);
                SummaryInfo summaryInfo = new SummaryInfo();
                summaryInfo.setEntryId(jsonObj.getString("id"));
                summaryInfo.setTitle(jsonObj.getString("title"));
                summaryInfo.setPublishTime(new Date(jsonObj.getLong("published")));
                summaryInfoList.add(summaryInfo);
            }
        } catch (JSONException e){
            e.printStackTrace();
        }
        return summaryInfoList;
    }
}
